<template>
  <div class="exam-page">
    <div class="header">
      <h2>{{ paper?.title || '加载中...' }}</h2>
    </div>

    <el-form :model="answers" ref="examFormRef" label-width="0">
      <el-card v-for="(question, index) in questions" :key="question.id" class="question-card">
        <template #header>
          <div class="question-header">
            <span>{{ index + 1 }}. {{ question.title }} ({{ typeMap[question.type] }})</span>
          </div>
        </template>

        <div class="question-content">{{ question.content }}</div>

        <el-form-item
          :prop="`answers.${question.id}`"
          :rules="getQuestionRules(question.type)"
        >
          <el-radio-group
            v-if="question.type === 'SINGLE_CHOICE'"
            v-model="answers[question.id]"
            @change="validateField(`answers.${question.id}`)"
          >
            <el-radio
              v-for="(option, key) in JSON.parse(question.options || '{}')"
              :key="key"
              :value="option"
            >
              {{ option }}
            </el-radio>
          </el-radio-group>

          <el-radio-group
            v-else-if="question.type === 'TRUE_FALSE'"
            v-model="answers[question.id]"
            @change="validateField(`answers.${question.id}`)"
          >
            <el-radio value="true">正确</el-radio>
            <el-radio value="false">错误</el-radio>
          </el-radio-group>

          <el-input
            v-else
            v-model="answers[question.id]"
            type="textarea"
            :rows="4"
            placeholder="请输入答案"
          ></el-input>
        </el-form-item>
      </el-card>

      <el-form-item>
        <el-button type="primary" @click="submitExam" :loading="submitting">提交试卷</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { usePaperStore } from '@/stores/api/paper';
import { usePaperSubmissionStore } from '@/stores/api/paper-submission';
import { useQuestionStore } from '@/stores/api/question';
import { useUserStore } from '@/stores/api/user';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const route = useRoute();
const router = useRouter();
const paperStore = usePaperStore();
const questionStore = useQuestionStore();
const paperSubmissionStore = usePaperSubmissionStore();
const userStore = useUserStore();

const paperId = computed(() => parseInt(route.params.paperId as string));

const typeMap = {
  SINGLE_CHOICE: '单选题',
  TRUE_FALSE: '判断题',
  TEXT: '大题',
};

const paper = ref(null);
const questions = ref([]);
const answers = ref({});
const submitting = ref(false);
const examFormRef = ref<FormInstance>();

// 根据题目类型动态生成验证规则
const getQuestionRules = (type: string): FormRules => {
  const rules: FormRules = {};

  if (type === 'TEXT') {
    rules[''] = [ // 空字符串作为键，因为实际字段名会在 :prop 中指定
      { required: true, message: '请输入答案', trigger: 'blur' },
      { min: 1, message: '答案不能为空', trigger: 'blur' }
    ];
  } else {
    rules[''] = [
      { required: true, message: '请选择答案', trigger: 'change' }
    ];
  }

  return rules;
};

// 手动触发字段验证
const validateField = (prop: string) => {
  if (!examFormRef.value) return;
  examFormRef.value.validateField(prop, () => {});
};

const fetchPaperAndQuestions = async () => {
  try {
    paper.value = await paperStore.fetchPaperById(paperId.value);
    const questionPromises = paper.value.questionIds.map(id => questionStore.fetchQuestionById(id));
    questions.value = await Promise.all(questionPromises);
    // 初始化答案对象，确保每个问题都有默认值
    questions.value.forEach(q => {
      if (answers.value[q.id] === undefined) {
        answers.value[q.id] = q.type === 'TEXT' ? '' : '';
      }
    });
  } catch (error) {
    ElMessage.error('加载试卷失败');
    router.go(-1);
  }
};

const submitExam = async () => {
  if (!examFormRef.value)
    return;
  if (!userStore.user?.id) {
    ElMessage.error('请先登录');
    return;
  }

  examFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const submission = {
          paperId: paperId.value,
          studentId: userStore.user.id,
          answers: Object.entries(answers.value).reduce((acc, [questionId, answer]) => {
            acc[Number(questionId)] = answer !== null && answer !== undefined ? String(answer) : '';
            return acc;
          }, {} as { [key: number]: string }),
        };
        await paperStore.submitPaper(submission);
        router.push('/front/exam');
      } catch (error) {
        // 提交失败处理
      } finally {
        submitting.value = false;
      }
    } else {
      ElMessage.error('请完成所有必填题目');
    }
  });
};

onMounted(() => {
  fetchPaperAndQuestions();
});
</script>

<style scoped>
.exam-page {
  width: 80%;
  margin: 40px auto 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  flex-grow: 1;
  text-align: center;
}
.question-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.question-header {
  font-size: 16px;
  color: #333;
}

.question-content {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.el-button {
  margin-right: 10px;
}
</style>